/*
 * @lc app=leetcode.cn id=107 lang=cpp
 *
 * [107] 二叉树的层序遍历 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  vector<vector<int>> levelOrderBottom(TreeNode* root)
  {
    map<int, vector<int>, greater<int>> m;
    Preorder(root, m, 0);
    vector<vector<int>> ans;
    for (auto itr = m.begin(); itr != m.end(); ++itr)
      ans.push_back(itr->second);
    return ans;
  }

  void Preorder(TreeNode* root, map<int, vector<int>, greater<int>>& m, int level)
  {
    if (root) {
      m[level].push_back(root->val);
      Preorder(root->left, m, level + 1);
      Preorder(root->right, m, level + 1);
    }
  }
};
// @lc code=end
